package com.card.mail;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.card.common.MessageComm;
import com.card.user.User;
import com.card.user.UserManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xiaoao.net.db.DBManager;
import com.xiaoao.net.db.Entity;
import com.xiaoao.net.db.FilterOperator;
import com.xiaoao.net.db.Query;
import com.xiaoao.net.db.Query.FilterPredicate;
import com.xiaoao.net.json.message.JsonMessage;
import com.xiaoao.net.utils.EntityUtils;
import com.xiaoao.net.utils.TimeUtils;
import com.xiaoao.net.utils.URLUtil;
import com.xiaoao.net.utils.json.GSONUtils;

/**
 * 邮件系统统一管理类
 * 
 * @author Administrator
 *
 */
public class MailManager {
	private static final MailManager instance = new MailManager();
	public static MailManager getInstance() {
		return instance;
	}

	public static final String T_MAIL_DATA = "maildata";

	public MailManager() {
		init();
	}
	// Enddate 大于当前 启动服务器时间的所有邮件
	private List<GlobMail> mailList = new ArrayList<>();
	// 上面list的map映射
	private Map<String, GlobMail> mailMap = new ConcurrentHashMap<>();

	public void sendNewMail(String mailJson) {
		String mailstr = null;
		mailstr = URLUtil.decodeUTF8(mailJson);
		if(mailstr != null){
			Gson gson = new GsonBuilder().setDateFormat(GSONUtils.DATEFORMAT)
//					.registerTypeAdapter(Base.class, Base.CreateGsonAdapter())
					.disableHtmlEscaping().create();
			String newMailJson = mailstr.replace("*", " ");
			GlobMail mail = gson.fromJson(newMailJson, GlobMail.class);
			mail.updateMailId();
			sendNewMail(mail);
		}
	}

	/**
	 * 游戏中添加邮件消息，并广播发送给所有客户
	 */
	public void sendNewMail(GlobMail mail) {
		// 判断是否符合开启时间
		if (mail.isFit()) {
			JsonMessage serverMsg = new JsonMessage(MessageComm.S2C_AddMail);
			serverMsg.addProperty("mail", mail);
			UserManager.getInstance().broadMessage(serverMsg);

			// 每个在线用户添加激活邮件
			for (User user : UserManager.getInstance().userMap.values()) {
				user.userMail().addReceveMail(mail);
			}
		}
		// 添加邮件到邮件列表
		mailList.add(mail);
		mailMap.put(mail.getMailId(), mail);
		// 添加数据库
		mail.saveDb();
	}

	public void testAddToDB(String content) {
		String rewardstr = "";
		// "100002, 100#203101, 3#400001, 10";

		Date endDate = TimeUtils.addDay(new Date(), 3);
		GlobMail mail = new GlobMail("xiaoaoGame", "testTitle1", content, rewardstr, new Date(), endDate);
		sendNewMail(mail);
	}

	/**
	 * 初始化,每天0点重新加载一次
	 */
	public void init() {
		List<GlobMail> dbList = getMailFromDB(true);
		this.mailList.clear();
		this.mailMap.clear();
		for (GlobMail globMail : dbList) {
			this.mailList.add(globMail);
			this.mailMap.put(globMail.getMailId(), globMail);
		}
		if(mailList.isEmpty()) {
			Date endDate = TimeUtils.addDay(new Date(), 10);
			for (int i = 0; i < 3; i++) {
				GlobMail mail = new GlobMail("xiaoaoGame", "testTitle"+i, "测试测试"+i, "", new Date(), endDate);
				sendNewMail(mail);
			}
		}
	}

	/**
	 * 获取所有邮件
	 * 
	 * @return json格式的邮件
	 */
	public String getMailsJson() {
		List<GlobMail> list = new ArrayList<>();
		for (GlobMail mail : getMailFromDB(true)) {
			list.add(mail);
		}
		Gson gson = new GsonBuilder().setDateFormat(GSONUtils.DATEFORMAT).disableHtmlEscaping().create();
		String mailsJosn = gson.toJson(list).trim();
		return mailsJosn;
	}
	
	/**
	 * 从数据库获取的邮件列表
	 * @param isAll 是否获取全部邮件
	 * @return
	 */
	public List<GlobMail> getMailFromDB(boolean isAll) {
		List<GlobMail> dbList = new ArrayList<>();
		// 从数据库获取玩家数据
		Query query = new Query(T_MAIL_DATA);
		if(isAll == false){
			query.addFilter(
					new FilterPredicate(GlobMail.ENDDATE, FilterOperator.GREATER_THAN, (long) new Date().getTime()));
		}
		query.setLimit(10000);
		List<Entity> mailEntityList = DBManager.getInstance().queryEntity(query);

		for (Entity entity : mailEntityList) {
			GlobMail globMail = new GlobMail(entity);
			dbList.add(globMail);
		}
		return dbList;
	}
	
	/*
	 * 返回没有过期的邮件
	 */
	public List<GlobMail> getCurMail() {
		List<GlobMail> nowList = new ArrayList<>();
		for (int i = 0; i < mailList.size(); i++) {
			GlobMail mail = mailList.get(i);
			if (mail.isFit()) {
				nowList.add(mail);
			}
		}
		return nowList;
	}

	/**
	 * 根据id获取邮件
	 * 
	 * @param id
	 * @return
	 */
	public GlobMail getMailMap(String id) {
		return mailMap.get(id);
	}

	/**
	 * 从数据库中删除邮件
	 * 
	 * @param id
	 */
	public void removeMail(String id) {
		GlobMail mail = mailMap.remove(id);
		if(mail != null) {
			mailList.remove(mail);
		}
		EntityUtils.Remove(T_MAIL_DATA, id);
	}

	public static void main(String[] args) {
		// MailManager.getInstance().testAddToDB("test");
		// List<GlobMail> mailList = MailManager.getInstance().getMailFromDB();
		// for (GlobMail globMail : mailList) {
		// System.out.println(new Gson().toJson(globMail));
		// }
		MailManager.getInstance().testAddToDB("test1");
	}
}
